package com.hcy.config;

import com.alibaba.fastjson.JSON;
import com.hcy.rabbitbasicmodel.model.ReturnResult;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author huchenying
 * Description:
 * @Date 2021/12/10 20:20
 */
@Component
public class CustomerAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final WebResponseExceptionTranslator<?> exceptionTranslator = new DefaultWebResponseExceptionTranslator();

    @SneakyThrows
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) {
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        ResponseEntity<?> res = exceptionTranslator.translate(authException);
        try {
            if (res.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                ReturnResult result = new ReturnResult();
                result.setCode(401);
                result.setMsg("未认证！");
                String s = JSON.toJSONString(result);
                response.getWriter().write(s);
            } else if (res.getStatusCode() == HttpStatus.FORBIDDEN) {
                ReturnResult result = new ReturnResult();
                result.setCode(403);
                result.setMsg("无权限！");
                String s = JSON.toJSONString(result);
                response.getWriter().write(s);
            } else {
                ReturnResult result = new ReturnResult();
                result.setCode(444);
                result.setMsg("请求失败！");
                String s = JSON.toJSONString(result);
                response.getWriter().write(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}